package com.rt.schedulenew.utils.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Objects;

public class JacksonUtil {

    private static final Logger logger = LogManager.getLogger(JacksonUtil.class);

    static ObjectMapper jsonMapper;
    static XmlMapper xmlMapper;

    static {

        jsonMapper = new ObjectMapper();
        xmlMapper = new XmlMapper();

    }


    public static String toJsonString(Object bean) {
        try {
            if (Objects.isNull(bean)) return null;
            return jsonMapper.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 将json字符串转成类型集合
     *
     * @param jsonStr         json字符串
     * @param itemClazz       类型
     * @param collectionClazz 集合类型
     * @param <T>
     * @return 返回集合列表
     */
    public static <T> Collection<T> readArrayValue(String jsonStr, Class<T> itemClazz, Class<? extends Collection> collectionClazz) {
        try {
            if (!StringUtils.hasText(jsonStr)) return null;
            CollectionType javaType = jsonMapper.getTypeFactory()
                    .constructCollectionType(collectionClazz, itemClazz);
            return jsonMapper.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 将json字符串转成对象
     *
     * @param jsonStr json字符串
     * @param clazz   类型
     * @param <T>
     * @return
     */
    public static <T> T readValue(String jsonStr, Class<T> clazz) {
        try {
            if (!StringUtils.hasText(jsonStr)) return null;
            return jsonMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            logger.error("解析json字符串失败!");
            return null;
        }
    }


    public static String toXmlString(Object bean) {
        try {
            if (Objects.isNull(bean)) return null;
            return xmlMapper.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public synchronized static <T> T readXmlValue(String xmlStr, Class<T> clazz) {
        try {
            if (!StringUtils.hasText(xmlStr)) return null;
            xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return xmlMapper.readValue(xmlStr, clazz);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

}
